package com.spica.spicaschool.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.asLiveData
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.switchMap
import com.spica.spicaschool.base.LiveCoroutinesViewModel
import com.spica.spicaschool.bean.news.News
import com.spica.spicaschool.network.repository.NewsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import javax.inject.Inject


@HiltViewModel
class NewsViewModel @Inject constructor(
    private val newsRepository: NewsRepository,
) : LiveCoroutinesViewModel() {

    private lateinit var _newsLiveData: LiveData<List<News>?>


    private val pageEntityStateFlow: MutableStateFlow<Int> = MutableStateFlow(1)

    val newsLiveData: LiveData<List<News>?>
        get() = _newsLiveData.distinctUntilChanged()

    fun fetchNews(
        onComplete: () -> Unit,
        onError: (String?) -> Unit
    ) {
        _newsLiveData = pageEntityStateFlow.asLiveData().switchMap {
            newsRepository.fetchNews(it, onComplete, onError).asLiveDataOnViewModelScope()
        }

    }

    /**
     * 切换页码
     */
    fun pageChanged(pageIndex: Int) {
        pageEntityStateFlow.value = pageIndex
    }


}